package main

import (
	"global/model"
	"github.com/ngaut/log"
	"srv/symbol/exchange"
	"global/core"
	"os"
	"strings"
)

type SymbolHandle struct {
	ctx 		*core.Context
	handles 	map[string]exchange.SymbolInterface
}

func NewSymbolHandle(ctx *core.Context) *SymbolHandle {
	return &SymbolHandle{
		ctx: ctx,
		handles: make(map[string]exchange.SymbolInterface)}
}

func (h *SymbolHandle) Run() {
	// 加载所有交易所
	exchanges, err := model.ExchangeModel.AllEnabled()
	if err != nil {
		log.Errorf("Error: load exchanges failed: %s", err)
		return
	}
	log.Infof("Load exchange length: %d", len(exchanges))
	h.handler(exchanges)
}

func (h *SymbolHandle) handler(exchanges []*model.Exchange) {
	coins := h.loadCoins()
	log.Infof("coin length: %d", len(coins))

	for _, v := range exchanges {
		log.Infof("start handle exchange: %s", v.Slug)
		f := exchange.Factory(h.ctx, coins, v)
		if f == nil {
			continue
		}
		f.Start()
		h.handles[v.Slug] = f
	}
}

// 加载币种
func (h *SymbolHandle) loadCoins() map[string]int {
	coins, err := model.CoinModel.All()
	if err != nil {
		log.Errorf("Error: %s", err)
		os.Exit(1)
	}

	coinMaps := make(map[string]int)
	for _, v := range coins {
		coinMaps[strings.ToLower(v.Symbol)] = v.Mid
	}

	return coinMaps
}

